var express = require('express')
var router = express.Router()
const sqlQuery = require('../../module/sqlQuery')
const { resJsonObject } = require('../../module/canshu')

/**
 * 返回所有分类类别数据
 */
async function getCategoryList() {
  const results = await sqlQuery('select * from news_category')
  return results
}

/* GET users listing. */
router.get('/', function (req, res, next) {
  res.render('admin/news/newsList')
})

router.get('/data', async function (req, res, next) {
  try {
    // keywords 搜索关键词 为空的时候 查询全部
    let { page, limit, keywords_title = '' } = req.query
    console.log(req.query)

    page = parseInt(page ? page : 1)
    limit = parseInt(limit)
    const results = await sqlQuery(
      `SELECT newslist.id as id,
      title,
      author,
      pubtime,
      content,
      categoryid,
      status,
      news_category.name as category_name,
      brief
      FROM newslist LEFT JOIN news_category ON newslist.categoryid=news_category.id where status=1 and title like ? limit ?,?`,
      ['%' + keywords_title + '%', (page - 1) * 5, limit]
    )

    // 符合条件的总条数
    const [
      { count_num },
    ] = await sqlQuery(
      'select count(*) as count_num from newslist where status=1 and title like ?',
      ['%' + keywords_title + '%']
    )

    res.json(
      resJsonObject({
        code: 0,
        msg: '完成',
        data: {
          arr: Array.from(results),
          count: count_num,
        },
      })
    )
    // res.render('admin/users/userlist',{userlist:results});
  } catch (error) {
    console.log(error);
    res.json(
      resJsonObject({
        code: 1,
        msg: '获取失败',
        data: {
          error,
        },
      })
    )
  }
})

// 信息界面 添加
router.get('/add', async function (req, res, next) {
  // 获取分类列表
  const categoryList = await getCategoryList()
  const options = { categoryList, newsinfo: { categoryid: 1 } }

  res.render('admin/news/addNews', options)
})

router.post('/add', async function (req, res, next) {
  try {
    console.log(req.body)
    const { title, author, pubtime, content, category_id } = req.body

    const sqlStr = `insert into newslist (title,author,pubtime,content,categoryid,status) values (?,?,?,?,?,?)`
    await sqlQuery(sqlStr, [
      title,
      author,
      pubtime,
      content,
      parseInt(category_id),
      1,
    ])
    // console.log(results)
    res.json(
      resJsonObject({
        code: 0,
        msg: '添加成功',
      })
    )
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '添加失败',
        data: {
          error,
        },
      })
    )
  }
})

// 用户信息删除（update状态改位为 0 ）
router.post('/delete', async function (req, res, next) {
  // console.log(req.body)
  const { id } = req.body

  // 用户信息删除（update状态改位为 0 ）
  // const { username, password, email, mobile, roleid } = req.body
  const results = await sqlQuery('update newslist set status = 0 where id=?', [
    id,
  ])
  res.json(
    resJsonObject({
      code: 0,
      msg: '删除成功',
      data: {
        results,
      },
    })
  )
})

// 信息界面 编辑
router.get('/edit/:id', async function (req, res, next) {
  let sqlStr = `select * from newslist where id=?`

  // 获取分类列表
  const categoryList = await getCategoryList()

  // 获取角色列表
  const results = await sqlQuery(sqlStr, [req.params.id])
  // res.json(results)
  const options = { newsinfo: results[0], categoryList }
  res.render('admin/news/editNews.ejs', options)
})

router.post('/edit', async function (req, res, next) {
  try {
    let { newsid, title, author, pubtime, content, category_id } = req.body

    // authlist = JSON.parse(authlist)

    // 1，更新角色表，
    const resultForRoleListTable = await sqlQuery(
      'update newslist set title =?,  author =?,  pubtime =?, content =?,categoryid =? where id=?',
      [title, author, pubtime, content, category_id, parseInt(newsid)]
    )

    // 2，更新角色权限关联表

    // // 先删除原有的该角色的权限信息
    // await sqlQuery('delete from role_auth where roleid=?', [roleid])

    // // 添加新的角色权限信息
    // authlist.forEach(async (item) => {
    //   await sqlQuery(`insert into role_auth (roleid,authid)
    //   values (${parseInt(roleid)},${parseInt(item.value)}); `)
    // })

    res.json(
      resJsonObject({
        code: 0,
        msg: '更新成功',
      })
    )
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '更新失败',
        data: {
          error,
        },
      })
    )
  }
})

// 分类管理==================================================

/* GET users listing. */
router.get('/news_category', function (req, res, next) {
  res.render('admin/news/categorylist')
})

router.get('/news_category/data', async function (req, res, next) {
  try {
    // keywords 搜索关键词 为空的时候 查询全部
    let { page, limit } = req.query
    console.log(req.query)

    page = parseInt(page ? page : 1)
    limit = parseInt(limit)
    const results = await sqlQuery('select * from news_category limit ?,?', [
      (page - 1) * 5,
      limit,
    ])

    // 符合条件的总条数
    const [{ count_num }] = await sqlQuery(
      'select count(*) as count_num from news_category'
    )

    console.log(results)

    res.json(
      resJsonObject({
        code: 0,
        msg: '完成',
        data: {
          arr: Array.from(results),
          count: count_num,
        },
      })
    )
    // res.render('admin/users/userlist',{userlist:results});
  } catch (error) {
    res.json(
      resJsonObject({
        code: 1,
        msg: '获取失败',
        data: {
          error,
        },
      })
    )
  }
})

// 信息界面 添加
router.get('/news_category/add', async function (req, res, next) {
  // 获取角色列表
  // const roleList = await getRoleList()
  res.render('admin/news/addCategory', {})
})

router.post('/news_category/add', async function (req, res, next) {
  try {
    console.log(req.body)
    const { category_name, category_brief } = req.body

    const sqlStr = `insert into news_category (name,brief) values (?,?)`
    await sqlQuery(sqlStr, [category_name, category_brief])
    // console.log(results)
    res.json(
      resJsonObject({
        code: 0,
        msg: '添加成功',
      })
    )
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '添加失败',
        data: {
          error,
        },
      })
    )
  }
})

// 用户信息删除（update状态改位为 0 ）
router.post('/news_category/delete', async function (req, res, next) {
  // console.log(req.body)
  const { id } = req.body

  // 用户信息删除（update状态改位为 0 ）
  // const { username, password, email, mobile, roleid } = req.body
  const results = await sqlQuery('delete from news_category where id=?', [id])
  res.json(
    resJsonObject({
      code: 0,
      msg: '删除成功',
      data: {
        results,
      },
    })
  )
})

// 信息界面 编辑
router.get('/news_category/edit/:id', async function (req, res, next) {
  let sqlStr = `select * from news_category where id=?`

  // 获取角色列表
  const results = await sqlQuery(sqlStr, [req.params.id])
  // res.json(results)
  const options = { categoryinfo: results[0] }
  res.render('admin/news/editCategory.ejs', options)
})

router.post('/news_category/edit', async function (req, res, next) {
  try {
    let { category_name, category_brief, category_id } = req.body

    // 1，更新表，
    const resultForRoleListTable = await sqlQuery(
      'update news_category set name =?,  brief =? where id=?',
      [category_name, category_brief, parseInt(category_id)]
    )

    res.json(
      resJsonObject({
        code: 0,
        msg: '更新成功',
      })
    )
  } catch (error) {
    console.log(error)
    res.json(
      resJsonObject({
        code: 1,
        msg: '更新失败',
        data: {
          error,
        },
      })
    )
  }
})

module.exports = router
